package com.uuj.dome.controller;

import com.uuj.dome.entity.UserEntity;
import com.uuj.dome.jpa.UserJpa;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * ClassName:UserController
 * PACKAGE_NAME:com.uuj.dome.controller
 */
@RestController
public class UserController {

    @Autowired
    private UserJpa jpa;

    @GetMapping("/list")
    public List<UserEntity> list() {
        return jpa.findAll();
    }

    @GetMapping("/add")
    public String add() {
        UserEntity entity = new UserEntity();
        entity.setAddress("李三");
        entity.setAge(23);
        entity.setName("哈哈哈");
        entity.setPassword("123");

        jpa.save(entity);
        return "用户信息添加成功";
    }

    @GetMapping("/delete")
    public String delete(int id) {
        jpa.deleteById(id);
        return "用户删除成功";
    }

    @GetMapping("/query/list")
    public List<UserEntity> queryList() {
        return jpa.nativeQuery(20);
    }

    @GetMapping("/query/delete")
    public String queryDelete() {
        jpa.queryDelete("哈哈哈", "123");
        return "用户删除成功";
    }

    @GetMapping(value = "/cutpage")
    public List<UserEntity> cutPage(int page, int size, String sortVal) {

        ////获取排序对象
        Sort.Direction sort_direction = Sort.Direction.ASC.toString().equalsIgnoreCase(sortVal) ? Sort.Direction.ASC : Sort.Direction.DESC;
        ////设置排序对象参数
        Sort sort = new Sort(sort_direction, "id");
        //创建分页对象
        PageRequest request = PageRequest.of(page - 1, size, sort);
        //执行分页查询
        List<UserEntity> content = jpa.findAll(request).getContent();
        content.forEach(userEntity -> {
            userEntity.setSize(size);
            userEntity.setPage(page);
        });
        return content;
    }
}
